﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Intex.Db.Models;
using System.IO;
using PrintAgentService;
using System.Threading;
using PMS.Log;

namespace PrintingManagerSystem
{
    public partial class SinglePrinterPrint : Form
    {
        public SinglePrinterPrint()
        {
            InitializeComponent();
        }

        public void Init(DataSet templateConfig, int printerCheckSpan)
        {
            dsTemplateConfig = templateConfig;
            //this.mapDicDic = mapDicDic;
            //printData = data;
            //this.dgvPrintData.DataSource = printData;
            this.printerCheckSpan = printerCheckSpan;
            //try
            //{
            //    string filterStr = Config.DisplayedColumn;
            //    var filters = filterStr.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
            //        .Select(k =>
            //            {
            //                if (mapDicDic.ContainsKey(k))
            //                {
            //                    return mapDicDic[k];
            //                }
            //                else
            //                {
            //                    return null;
            //                }
            //            });
            //    if (filters.Count() > 0)
            //    {
            //        for (int i = 0; i < this.dgvPrintData.Columns.Count; i++)
            //        {
            //            if (!filters.Any(it => it.ItemName == this.dgvPrintData.Columns[i].Name))
            //            {
            //                this.dgvPrintData.Columns[i].Visible = false;
            //            }
            //        }
            //    }
            //}
            //catch
            //{
            //}

        }

        DataTable printData = null;
        Dictionary<string, ItemType> mapDic = null;
        DataSet dsTemplateConfig = null;
        public int printerCheckSpan = 3000;

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (this.lvPrintDetail.CheckedItems.Count <= 0)
            {
                MessageBox.Show("请选择要再次打印的记录");
                return;
            }
            foreach (var item in Properties.Settings.Default.PrinterList)
            {
                try
                {
                    if (Config.IsCheckedWhenSimplePrinter && !CPrintStatus.IsPrinterReady(item, printerCheckSpan))
                    {
                        MessageBox.Show(string.Format("错误！请检查打印机{0}", item));
                        return;
                    }
                }
                catch
                {
                    MessageBox.Show(string.Format("错误！请检查打印机{0}", item));
                    return;
                }
            }

            PrintAgent pa = new PrintAgent();
            if (printData != null
                && printData.Columns.Contains("TemplateFile")
                && printData.Rows.Count > 0)
            {
                //this.dgvPrintData.DataSource = printData;
                var m = pa.GetItemTypes();

                if (!printData.Columns.Contains(m[Config.IndexAlias]))
                {
                    printData.Columns.Add(m[Config.IndexAlias]);
                }
                if (!printData.Columns.Contains(m[Config.NameAlias]))
                {
                    printData.Columns.Add(m[Config.NameAlias]);
                }
                if (!printData.Columns.Contains(m[Config.CreatedAlias]))
                {
                    printData.Columns.Add(m[Config.CreatedAlias]);
                }

                for (int i = 0; i < printData.Rows.Count; i++)
                {
                    printData.Rows[i][m[Config.IndexAlias]] = this.nudIndex.Value.ToString().PadLeft(Config.IndexLength, '0');
                    printData.Rows[i][m[Config.NameAlias]] = this.cmbMark.SelectedItem.ToString();
                    printData.Rows[i][m[Config.CreatedAlias]] = this.dtpDate.Value.ToString("yyyyMMdd");
                    pa.JoinRowsField(printData.Rows[i], mapDic.Values.Where(x => x.ItemDataType.StartsWith("join")).ToList(), m);
                }
                //控制打印次数
                for (int iprint = 0; iprint < (int)this.nudPrintNum.Value; iprint++)
                {
                    int nowPrinterIndex = 0;
                    //打印每条记录
                    for (int i = 0; i < printData.Rows.Count; i++)
                    {
                        int newRowIndex = i;
                        var row = printData.Rows[newRowIndex];

                        bool selectedPrint = false;
                        for (int j = 0; j < this.lvPrintDetail.CheckedItems.Count; j++)
                        {
                            if (this.lvPrintDetail.CheckedItems[j].Text == row[mapDic[Config.LocalColumn].ItemName].ToString())
                            {
                                selectedPrint = true;
                            }
                        }
                        if (!selectedPrint)
                        {
                            nowPrinterIndex++;
                            if (nowPrinterIndex >= Properties.Settings.Default.PrinterList.Count) nowPrinterIndex = 0;
                            continue;
                        }
                        var templateFilePath = PrintAgent.TemplateFilePath + "Simple\\" + row["TemplateFile"].ToString();
                        if (File.Exists(templateFilePath))
                        {
                            try
                            {
                                var tempFile = pa.PrintLabel(templateFilePath, mapDic, row, dsTemplateConfig);
                                GC.Collect();
                                //测试打印机状态
                                if (Config.IsCheckedWhenSimplePrinter && !CPrintStatus.IsPrinterReady(Properties.Settings.Default.PrinterList[nowPrinterIndex], printerCheckSpan))
                                {
                                    MessageBox.Show(string.Format("错误！请检查打印机{0}", Properties.Settings.Default.PrinterList[nowPrinterIndex]));
                                    //如果失败，继续检测状态
                                    while (!CPrintStatus.IsPrinterReady(Properties.Settings.Default.PrinterList[nowPrinterIndex], printerCheckSpan))
                                    {
                                        Application.DoEvents();
                                        Thread.Sleep(1000);
                                    }
                                }
                                pa.PrintExcel(tempFile, Properties.Settings.Default.PrinterList[nowPrinterIndex]);
                                GC.Collect();
                                Thread.Sleep(1000);
                                Application.DoEvents();
                            }
                            catch(Exception ex)
                            {
                                Logger.Error(ex);
                            }
                        }
                        nowPrinterIndex++;
                        if (nowPrinterIndex >= Properties.Settings.Default.PrinterList.Count) nowPrinterIndex = 0;
                    }
                }
            }

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void SinglePrinterPrint_Load(object sender, EventArgs e)
        {
            PrintAgent pa = new PrintAgent();
            var mapDic = pa.GetItemTypes();
            this.lbIndex.Text = mapDic[Config.IndexAlias] + "：";
            this.lbMark.Text = mapDic[Config.NameAlias] + "：";
            this.lbDate.Text = mapDic[Config.CreatedAlias] + "：";
            var markList = pa.GetTemplateValues();
            this.cmbMark.DataSource = markList;
        }

        private void cmbMark_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.lvDetail.Items.Clear();
            this.lvPrintDetail.Items.Clear();
            if (this.cmbMark.SelectedIndex >= 0)
            {
                PrintAgent pa = new PrintAgent();
                var m = pa.GetItemTypes();
                var content = pa.GetTemplateValue(this.cmbMark.SelectedItem.ToString(), out mapDic);
                if (content != null && content.Rows.Count > 0)
                {
                    try
                    {
                        string filterStr = Config.DisplayedColumn;
                        var filters = filterStr.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
                            .Select(k =>
                            {
                                if (mapDic.ContainsKey(k))
                                {
                                    return mapDic[k];
                                }
                                else
                                {
                                    return null;
                                }
                            });
                        if (filters.Count() > 0)
                        {
                            for (int i = 0; i < content.Columns.Count; i++)
                            {
                                if (filters.Any(it => it.ItemName == content.Columns[i].ColumnName))
                                {
                                    ListViewItem lvi = new ListViewItem();
                                    lvi.Text = filters.First(it => it.ItemName == content.Columns[i].ColumnName).ItemName;
                                    lvi.SubItems.Add(new ListViewItem.ListViewSubItem() { Text = content.Rows[0][content.Columns[i].ColumnName].ToString() });
                                    this.lvDetail.Items.Add(lvi);
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                    for (int i = 0; i < content.Rows.Count; i++)
                    {
                        this.lvPrintDetail.Items.Add(content.Rows[i][m[Config.LocalColumn]].ToString());
                    }
                    printData = content;
                }
            }

        }
    }
}
